<?php
/**
 * Created by PhpStorm.
 * User: zhendong
 * Date: 2017/4/17
 * Time: 9:50
 */
namespace Backend\Model;
use Think\Model;

class AdOrderModel extends Model
{
    protected $ad_delivery_model;
    public function __construct() {
        parent::__construct();
        $this->ad_delivery_model = D('AdDelivery');
    }

    /**
     * 自动验证
     * @var array
     */
    protected $_validate = [
        //array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间])
        array('order_name', 'require', '请填写订单名称！'),
        array('order_name', '', '订单名称已存在！', 0, 'unique', 3),
        array('sale_mode', 'require', '请选售卖方式！', '', '', 3),
        array('start_time', 'require', '请选择开始时间！'),
        array('end_time', 'require', '请选择结束时间！'),
        array('cid', 'require', '请选择广告客户！'),
        //array('contract_number', 'require', '请填写合同编号！'),
    ];


    protected function _before_insert(&$data) {
        $data['ctime']=time();
        $data['user_id'] =$_SESSION['id'];
    }

    protected function _before_update(&$data) {
        $data['ctime']=time();
    }

    /**
     * 此方法只操作当前表
     * @param array $where
     * @param string $field
     * @return mixed
     */
    public function get_ad_order_info($where = [], $field = '') {
        if(!empty($where) && is_array($where)) {
            return $this->where($where)->field($field)->order('id DESC')->select();
        } else {
            return $this->order('id DESC')->select();
        }
    }

    /**
     * //此方法获取与之关联的表的数据
     * @param array $where
     * @param string $limit
     * @return array
     */
    public function get_ad_order_all($where = [], $limit = '' ) {
        $where = array('user_id' =>$_SESSION['id']);
        $data = $this->alias('o')
            ->join('left join dsp_customer c on o.cid=c.id')
            ->field("o.*, c.id as ccid, c.name")->where($where)
            ->limit($limit)->order('o.id DESC')->select();

        return $this->get_id_str($data);
    }

    /**
     * 获取id 并调用 data_format 方法 【耦合度较高 后期调优】
     * @param $data         原始数据
     * @return array
     */
    public function get_id_str($data) {
        $str = '';
        foreach ($data as $k => $v) {
            $str .= $v['id'].',';
        }
        $str = rtrim($str ,',');

        $condition['order_id'] = array('in', $str);
        $res = $this->ad_delivery_model->where($condition)->field('id, delivery_state, order_id')->select();

        $result = $this->data_format($data, $res);

        return $result;

    }

    /**
     * 订单数据格式化方法
     * @param   $arr1       订单数据
     * @param   $arr2       广告投放数据
     * @return  array       格式化后的数据
     */
    public function data_format($arr1, $arr2) {
        $data = [];
        foreach ($arr1 as $k1 => $v1) {
            $id         = $v1['id'];			    //获得变量
            $state      = [];				        //定义状态
            $ids1       = '';					    //定义id字符串存放地址
            $ids2       = '';
            $n          = 0;						//定义计数器
            $m          = 0;						//定义计数器

            foreach ($arr2 as $k2 => $v2) {
                if ($id == $v2['order_id']) {
                    if ($v2['delivery_state'] == 0) {
                        $n++;
                        $ids1 .= $v2['id'].',';

                        $state['delivery'][$v2['delivery_state']] = [
                            'state' => $v2['delivery_state'],
                            'ids' => $ids1, 'count' => $n,
                            'order_id' => $v2['order_id']
                        ];

                    } elseif ($v2['delivery_state'] == 4) {
                        $m++;
                        $ids2 .= $v2['id'].',';

                        $state['delivery'][$v2['delivery_state']] = [
                            'state' => $v2['delivery_state'],
                            'ids' => $ids2, 'count' => $m,
                            'order_id' => $v2['order_id']
                        ];

                    }
                }
            }
            $data[] = array_merge($arr1[$k1], $state);
        }
        return $data;
    }

}